

package com.kimo.shop.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.enums.OfflineHandleEventType;
import com.kimo.shop.bean.enums.ProdStatusEnums;
import com.kimo.shop.bean.enums.ProdType;
import com.kimo.shop.bean.model.OfflineHandleEvent;
import com.kimo.shop.bean.model.ProdLang;
import com.kimo.shop.bean.model.Product;
import com.kimo.shop.bean.model.Sku;
import com.kimo.shop.bean.param.ProductParam;
import com.kimo.shop.bean.param.ProductScoreParam;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.i18n.I18nMessage;
import com.kimo.shop.common.i18n.LanguageEnum;
import com.kimo.shop.common.util.Json;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.security.admin.util.SecurityUtils;
import com.kimo.shop.service.*;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 商品列表、商品发布controller
 *
 * @author kimo-taozhouchuan
 */
@Controller
@RequestMapping("/admin/scoreProduct")
@AllArgsConstructor
public class ScoreProductController {

    private final ProductService productService;
    private final SkuService skuService;
    private final ProdLangService prodLangService;
    private final BasketService basketService;
    private final OfflineHandleEventService offlineHandleEventService;
    private final MapperFacade mapperFacade;


    /**
     * 分页获取积分商品信息
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('score:prod:page')")
    public ResponseEntity<IPage<Product>> page(ProductParam product, PageParam<Product> page) {
//            IPage<Product> products = productService.page(page,
//                new LambdaQueryWrapper<Product>()
//                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
//                        .eq(product.getStatus() != null, Product::getStatus, product.getStatus())
//                        .orderByDesc(Product::getPutawayTime)
//                        .eq(Product::getProdType, ProdType.PROD_TYPE_SCORE.value())
//                        .ne(Product::getStatus,-1));
//        System.out.println("---------"+ProdType.PROD_TYPE_SCORE);
        product.setLang(I18nMessage.getDbLang());
        product.setShopId(SecurityUtils.getSysUser().getShopId());
        product.setProdType(ProdType.PROD_TYPE_SCORE.value());
        IPage<Product> products = productService.pageByLang(page,product);
        return ResponseEntity.ok(products);
    }


    /**
     * 获取信息
     */
    @GetMapping("/info/{prodId}")
    @PreAuthorize("@pms.hasPermission('score:prod:info')")
    public ResponseEntity<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        List<Sku> skuList = skuService.listByProdId(prodId, I18nMessage.getDbLang());
        prod.setSkuList(skuList);
        // 获取语言列表
        List<ProdLang> prodLangList = prodLangService.list(new LambdaQueryWrapper<ProdLang>().eq(ProdLang::getProdId, prodId));
        prod.setProdLangList(prodLangList);
        return ResponseEntity.ok(prod);
    }

    /**
     * 平台删除商品
     */
    @DeleteMapping("/{prodId}")
    @PreAuthorize("@pms.hasPermission('score:prod:delete')")
    public ResponseEntity<Void> delete(@PathVariable("prodId") Long prodId) {
        Product dbProduct = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId(), I18nMessage.getDbLang());

        // 删除商品
        productService.removeProductByProdId(prodId);

        // 删除商品缓存
        productService.removeProdCacheByProdId(prodId, LanguageEnum.LANGUAGE_EN.getLang());
        productService.removeProdCacheByProdId(prodId,LanguageEnum.LANGUAGE_ZH_CN.getLang());

        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }

        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }

        return ResponseEntity.ok().build();
    }



    /**
     * 通过prodId获取最新下线商品的事件
     */
    @GetMapping("/getOfflineHandleEventByProdId/{prodId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByProdId(@PathVariable Long prodId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.PROD.getValue(), prodId);
        return ResponseEntity.ok(offlineHandleEvent);
    }


    /**
     * 更新商品状态
     */
    @PutMapping("/prodStatus")
    public ResponseEntity<Void> shopStatus(@RequestBody ProductParam productParam) {
        Long prodId = productParam.getProdId();
        Integer prodStatus = productParam.getStatus();
        Product dbProduct = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        if (!(Objects.equals(dbProduct.getStatus(), ProdStatusEnums.NORMAL.getValue())
                || Objects.equals(dbProduct.getStatus(), ProdStatusEnums.SHOP_OFFLINE.getValue()))) {
            // 商品不在正常状态，修改失败
            throw new KimoShopBindException("kimo.group.prod.status.error");
        }
        skuService.checkPartyCode(productParam.getSkuList(),true);
        Product product = new Product();
        product.setProdId(prodId);
        product.setStatus(prodStatus);
        if (prodStatus == 1) {
            product.setPutawayTime(new Date());
        }
        dbProduct.setStatus(prodStatus);
        // 商品状态改变时的发送事件，让活动下线
//        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, dbProduct.getStatus()));

        productService.updateById(product);
        List<String> userIds = basketService.listUserIdByProdId(prodId);
        productService.removeProdCacheByProdId(prodId, LanguageEnum.LANGUAGE_EN.getLang());
        productService.removeProdCacheByProdId(prodId,LanguageEnum.LANGUAGE_ZH_CN.getLang());
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 保存积分商品
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('score:prod:save')")
    public ResponseEntity<String> save(@Valid @RequestBody ProductScoreParam productScoreParam) {
        checkParam(productScoreParam);
        skuService.checkPartyCode(productScoreParam.getSkuList(),false);
        Product product = mapperFacade.map(productScoreParam, Product.class);
        product.setStatus(1);
        product.setShopId(Constant.PLATFORM_SHOP_ID);
        product.setPutawayTime(new Date());
        product.setUpdateTime(new Date());
        product.setProdType(3);
        product.setVersion(0);
        product.setDeliveryMode(Json.toJsonString(productScoreParam.getDeliveryModeVo()));
        product.setCreateTime(new Date());
        // 商品销量设置为0
        product.setSoldNum(0);
        //积分商品类型
        product.setProdType(ProdType.PROD_TYPE_SCORE.value());
        ProductParam productParam = mapperFacade.map(productScoreParam,ProductParam.class);
        productService.saveProduct(product, productParam);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改积分商品
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('score:prod:update')")
    public ResponseEntity<String> update(@Valid @RequestBody ProductScoreParam productScoreParam) {
        checkParam(productScoreParam);
        Product product = mapperFacade.map(productScoreParam, Product.class);
        List<String> userIds = basketService.listUserIdByProdId(product.getProdId());
        Product dbProduct = productService.getProductByProdId(productScoreParam.getProdId(), I18nMessage.getDbLang());
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId(), I18nMessage.getDbLang());
        product.setUpdateTime(new Date());
        //积分商品类型
        product.setProdType(ProdType.PROD_TYPE_SCORE.value());
        dbProduct.setSkuList(dbSkus);
        ProductParam productParam = mapperFacade.map(productScoreParam,ProductParam.class);
        productService.updateProduct(productParam, dbProduct);
        productService.removeProdCacheByProdId(productParam.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        productService.removeProdCacheByProdId(productParam.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
        //清除缓存
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }
        return ResponseEntity.ok().build();
    }


    private void checkParam(ProductScoreParam productScoreParam) {
        boolean isAllUnUse = true;
        List<Sku> skuList = productScoreParam.getSkuList();
       /* for (Sku sku : skuList) {
            if (sku.getStatus() == Constant.SUPER_ADMIN_ID) {
                isAllUnUse = false;
            }
        }
        if (isAllUnUse) {
            // 至少要启用一种商品规格
            throw new KimoShopBindException("kimo.product.enable.sku");
        }*/
        for (Sku sku : skuList) {
            if (sku.getStatus() == Constant.SUPER_ADMIN_ID) {
                isAllUnUse = false;
            } else {
                isAllUnUse = true;
            }
        }
        if (isAllUnUse) {
            // 至少要启用一种商品规格
            throw new KimoShopBindException("kimo.product.enable.sku");
        }
    }

}
